<?php
/**
 * Created by lzl
 * Date: 2021 2021/9/9
 * Time: 14:46
 */
namespace App\Forms;

use App\Exceptions\RequestException;
use App\Models\Good;
use App\Models\GoodsBranch;
use App\Models\GoodsCategory;
use App\Models\GoodsSku;
use App\Models\GoodsSkuAttribute;
use App\Models\GoodsSkuDetail;
use App\Models\GoodsSpu;
use App\Models\GoodsStockLog;
use App\Models\User;
use Illuminate\Database\Query\Builder;

class GoodsForms extends BaseForm
{

    /**
     * @param $validated
     * @param array $field
     * @return mixed
     */
    public function getGoodsList($validated, $field = [])
    {

        $list = Good::where(function($q) use ($validated){
           /**
            * @var Builder $q
            */
            if(isset($validated['name']) && filled($validated['name'])){
                $q->where('goods_name','like',"%{$validated['name']}%");
            }

            if(isset($validated['status'])){
                $q->where('status', $validated['status']);
            }

            if(isset($validated['cat_id'])){
                $q->where('cat_id', $validated['cat_id']);
            }

            return $q;
        })->page(function($q) use ($validated){

            if(isset($validated['page']) && isset($validated['limit'])){
                $q->page($validated['page'], $validated['limit']);
            }

            return $q;
        })->orderBy('sort','desc')
          ->orderBy('id','desc')
          ->get($field ?: '*');

        return $list;

    }


    /**
     * 商品详情
     * @param $id
     * @return Good|\Illuminate\Database\Eloquent\Model
     */
    public function getGoodsDetail($id)
    {
        return Good::firstOrNew(['id' => $id ?: 0]);
    }


    /**
     * 商品详情
     * @param $id
     * @param array $field
     * @return Good|mixed
     */
    public function getGoodsDetailById($id, $field = ["*"])
    {
        return Good::find($id, $field);
    }


    /**
     * 商品sku详情
     * @param $id
     * @return array
     */
    public function getGoodsSkuDetail($id)
    {
        $goods = $this->getGoodsDetail($id)->toArray();

        $user = (new UserForms())->getUserDetail(UID);

        if($goods['is_single'] == Good::SINGLE){

            $attribute = GoodsSkuAttribute::where('goods_id', $id)->first();
            $market_price = (new GoodsAttributeForms())->dealPrice($user, $attribute);

            $attribute = $attribute->toArray();

            $attribute['market_price'] = $market_price;
            $goods['sku'] = [$attribute];

        }else{

            $skuDetail = GoodsSkuDetail::where('goods_id', $id)->get();

            $skuAttribute = GoodsSkuAttribute::where('goods_id', $id)->get([
                'id', 'goods_id', 'attribute_name', 'stock', 'price', 'market_price', 'partner_price', 'distributor_price',
                'sku_images', 'weight'
            ]);

            if(filled($skuDetail) && filled($skuAttribute)){

                $skuDetail = $skuDetail->toArray();

                $skuAttribute = $skuAttribute->toArray();

                foreach ($skuDetail as &$item){

                    $item['sku_detail'] = [];

                    foreach ($skuAttribute as $k2 => &$v2){

                        switch ($user->level){
                            case User::L_DISTRIBUTOR:
                                $market_price  = $v2['distributor_price'];
                                break;
                            case User::L_PARTNER:
                                $market_price  = $v2['partner_price'];
                                break;
                            default:
                                $market_price  = $v2['market_price'];
                                break;
                        }

                        $v2['market_price'] = $market_price;
                        $v2['attribute_name_list'] = json_decode($v2['attribute_name'], true) ?? [];
                        if(count($v2['attribute_name_list'] )){

                            foreach ($v2['attribute_name_list']  as $k3 => $v3){

                                if(array_key_exists($item['id'], $v3)){
                                   array_push($item['sku_detail'], $v3[array_key_first($v3)]);
                                }
                            }

                        }

                    }
                    $item['sku_detail'] = array_values(array_unique($item['sku_detail']));
                }

            }

            $goods['sku'] = $skuAttribute;
            $goods['sku_attribute'] = $skuDetail;
        }


        return $goods;


    }

    /**
     * 商品详情
     * @param $validated
     * @return array
     */
    public function getGoodsDetailForms($validated)
    {
        $model = $this->getGoodsDetail($validated['id'] ?? 0);

        $branch = GoodsBranch::get();

        $category = GoodsCategory::where('pid',0)->get();

        $children_category = GoodsCategory::where('pid', $model->category->pid ?? 0)->get();

        $sku = GoodsSku::get();

        if($model->is_single == Good::SINGLE_MORE){
            $sku_detail = GoodsSkuDetail::where('goods_id', $model->id)->get()->toArray();

            $sku_attribute = GoodsSkuAttribute::where('goods_id', $model->id)->get()->toArray();

            foreach ($sku_detail as &$v) {

                $details = [];

                foreach ($sku_attribute as $k => &$item) {

                    $attribute_name = json_decode($item['attribute_name'], true);

                    $item['attribute_array'] = $attribute_name;

                    foreach ($attribute_name as $k2 => $item2){
                        if(array_key_first($item2) == $v['id']){
                            array_push($details, $item2[$v['id']]);
                        }
                    }
                }

                $v['details']  = array_unique($details);
            }

        }else{

            $sku_detail = '';

            $sku_attribute = GoodsSkuAttribute::firstOrNew(['goods_id' =>  $model->id]);
        }

        $spu = GoodsSpu::where('goods_id', $model->id)->get();

        return compact('model','branch', 'category', 'children_category', 'sku', 'sku_detail', 'sku_attribute', 'spu');
    }


    /**
     * 修改商品基本信息
     * @param $validated
     * @throws RequestException
     * @throws \Throwable
     */
    public function editGoods($validated)
    {

        \DB::beginTransaction();
        try {
            $goods = Good::updateOrCreate(['id' => $validated['id'] ?? 0], $validated);

            if ($goods instanceof Good) {
                $goods_id = $goods->id;
            } else {
                $goods_id = $validated['id'];
            }

            //TODO sku这一块还是设计的不好，下次再优化
            if (isset($validated['sku'])) {

                $sku = $validated['sku'];

                if($validated['is_single'] == Good::SINGLE){

                    GoodsSkuAttribute::updateOrCreate(['goods_id' => $goods_id], array_merge(['goods_id' => $goods_id], $sku) );
                }else{
                    if (is_array($sku) && count($sku) ) {

                        if (isset($sku['sku_detail']) && is_array($sku['sku_detail'])) {

                            GoodsSkuAttribute::where('goods_id', $goods_id)->delete();

                            GoodsSkuDetail::where('goods_id', $goods_id)->delete();

                            $detail_id = [];
                            foreach ($sku['sku_detail'] as $item) {
                                $res = GoodsSkuDetail::create([
                                    'value'    => $item,
                                    'goods_id' => $goods_id
                                ]);
                                array_push($detail_id, $res->id);
                            }

                            unset($sku['sku_detail']);
                            foreach ($sku as &$item) {
                                $attribute_name = [];
                                foreach ($item['attribute_name'] as $k => $v) {
                                    $attribute_name[] = [$detail_id[$k] => $v];
                                }
                                $item['attribute_name'] = json_encode($attribute_name, JSON_UNESCAPED_UNICODE);
                                $item['goods_id'] = $goods_id;
                                GoodsSkuAttribute::create($item);
                            }

                        }

                    }
                }
            }

            if(isset($validated['spu']) && count($validated['spu'])){
                GoodsSpu::where('goods_id', $goods_id)->delete();
                foreach ($validated['spu'] as $spu){
                    GoodsSpu::create(array_merge(compact('goods_id'), $spu));
                }
            }

            //修改商品时 删除该商品下的分享图片
            (new UserForms())->deleteUserShareCode(['goods_id' => $goods->id]);

            \DB::commit();
        }catch (\Exception $e){
            \DB::rollBack();

            throw new RequestException($e->getMessage());
        }

    }


    /**
     * 库存变更记录
     * @param $goods_id
     * @param $count
     * @param $type
     * @return GoodsStockLog|\Illuminate\Database\Eloquent\Model
     */
    public static function stockUpdate($goods_id, $count, $type)
    {
        return GoodsStockLog::create(compact('goods_id','count','type'));
    }


    /**
     * 库存记录
     * @param $validated
     * @return mixed
     */
    public function getStockLogList($validated)
    {
        $list = GoodsStockLog::where('goods_id', $validated['id'])
            ->page($validated['page'], $validated['limit'])
            ->orderBy('id', 'desc')
            ->get();
        return $list;
    }


    /**
     * 删除商品（软删除）
     * @param $validated
     * @return int
     */
    public function deleteGoods($validated)
    {
        return Good::destroy($validated['id']);
    }


    /**
     * 分类列表
     * @param $validated
     * @return mixed
     */
    public function getCategoryList($validated)
    {
        $list = GoodsCategory::where(function ($q) use ($validated) {
            /**
             * @var Builder $q
             */
            if(isset($validated['level'])){
                $q->where('pid', '>', '0');
            }

        })->page(function ($q) use ($validated) {

            if (isset($validated['page']) && isset($validated['limit'])) {
                $q->page($validated['page'], $validated['limit']);
            }

            return $q;

        })->orderBy('sort', 'desc')->get();

        return $list;
    }


    public function getCateChildren()
    {
        return GoodsCategory::where('pid', '>', '0')
            ->orderBy('sort', 'desc')
            ->select(['id', 'category_name', 'images', 'sort'])
            ->get();
    }

    /**
     * 获取分类详情
     * @param $validated
     * @return array
     */
    public function getCategoryOrNew($validated)
    {
        $model = GoodsCategory::firstOrNew(['id' => $validated['id'] ?? 0]);

        $parents = GoodsCategory::where('pid',0)->get();

        return compact('model','parents');
    }


    /**
     * 修改分类
     * @param $validated
     * @return GoodsCategory|\Illuminate\Database\Eloquent\Model
     */
    public function editCategory($validated)
    {
        return GoodsCategory::updateOrCreate(['id' => $validated['id'] ?? 0 ], $validated);
    }


    /**
     * 删除分类
     * @param $validated
     * @return bool|mixed|null
     * @throws RequestException
     */
    public function deleteCategory($validated)
    {
        if(Good::where('cat_id', $validated['id'])->exists()){
            throw new RequestException(trans('message.goods.category_delete_error'));
        }

        return GoodsCategory::whereKey($validated['id'])->delete();
    }


    /**
     * 品牌列表
     * @param $validated
     * @return mixed
     */
    public function getBranchList($validated)
    {
        $list = GoodsBranch::where([])
            ->page($validated['page'], $validated['limit'])
            ->orderBy('id','desc')
            ->get();
        return $list;
    }


    /**
     * 修改品牌
     * @param $validated
     * @return GoodsBranch|\Illuminate\Database\Eloquent\Model
     */
    public function editBranch($validated)
    {
        return GoodsBranch::updateOrCreate(['id' => $validated['id'] ?? 0 ], $validated);
    }


    /**
     * 删除品牌
     * @param $validated
     * @return bool|mixed|null
     * @throws RequestException
     */
    public function deleteBranch($validated)
    {
        if(Good::where('branch_id', $validated['id'])->exists()){
            throw new RequestException(trans('message.goods.branch_delete_error'));
        }

        return GoodsBranch::whereKey($validated['id'])->delete();
    }


    /**
     * 获取品牌详情
     * @param $validated
     * @return GoodsBranch|\Illuminate\Database\Eloquent\Model
     */
    public function getBranchOrNew($validated)
    {
        return GoodsBranch::firstOrNew(['id' => $validated['id'] ?? 0]);
    }


    /**
     * 获取分类树
     * @return \Illuminate\Support\Collection
     */
    public function getCategoryTree($validated)
    {
        $category_field = ['id', 'pid', 'category_name'];

        $category = GoodsCategory::where('pid', $validated['category_id'])
            ->orderBy('sort', 'desc')
            ->get($category_field);

        return $category;

    }

}